<?php
/**
 * Created by PhpStorm.
 * User: zhengze
 * Date: 2019/7/1
 * Time: 18:29
 */

namespace app\admin\validate;

use app\api\enum\ScopeEnum;
use common\exception\CategoryException;
use common\exception\ExceptionEmun;
use app\common\model\Category;
use common\Token\Token;
use common\traits\InstanceTrait;
use common\validate\BaseValidate;

/**
 * Class CategoryValidate
 */
class CategoryValidate extends BaseValidate
{
    use InstanceTrait;

    protected $rule = [
        'id|参数' => ['require',],
        'ids|参数' => ['require',],
        'status|状态' => ['require',],
        'title|标题' => ['require',],
    ];

    protected $sceneRule = [
        'index' => [
            'only' => [''],
        ],
        'read' => [
            'only' => ['id'],
        ],
        'delete' => [
            'only' => ['id'],
        ],
        'deletes' => [
            'only' => ['ids'],
        ],
        'enables' => [
            'only' => ['ids', 'status'],
        ],
        'save' => [
            'only' => ['title'],
            'append' => [
                'title' => 'checkTitleUnique',
            ],
        ],
        'update' => [
            'only' => ['title', 'id'],
            'append' => [
                'title' => 'checkTitleUnique',
            ],
        ],
    ];

    /**
     * 检测名字重复
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    protected function checkTitleUnique($value, $rule, $data = [])
    {
        $admin_info = Token::instance()->getUserInfo();
        $category = Category::where('title', '=', $value)
                            ->where('creater_id', '=', $admin_info['admin_id'])
                            ->find();
        $pk = 'id';
        if (!empty($category)) {
            if (!empty($data[$pk])) {
                //修改
                if ($data[$pk] != $category['category_id']) {
                    return ExceptionEmun::getExctprion(CategoryException::NAME_REPEAT);
                }
            } else {
//                创建
                return ExceptionEmun::getExctprion(CategoryException::NAME_REPEAT);
            }
        }
        return true;
    }
}